/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.slice.tabbar.tabsegment;

import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSlider;
import ohos.agp.components.PageSliderProvider;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import com.xuexiang.xui_lib.component.tabbar.TabSegment;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.slice.BaseAbilitySlice;
import com.xuexiang.xuidemo.util.XToastUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 内容自适应
 *
 * @since 2021-04-21
 */
public class TabSegmentScrollableModeSlice extends BaseAbilitySlice {
    private TabSegment mTabSegment;
    private PageSlider mContentViewPager;
    private PageSliderProvider mPagerAdapter;
    private static final int TAB_COUNT = 10;
    private int mCurrentItemCount = TAB_COUNT;
    private String[] pages = MultiPage.getPageNames();
    private Map<MultiPage, Component> mPageMap = new HashMap<>();

    @Override
    protected int getUIContentLayoutId() {
        return ResourceTable.Layout_slice_tab_segment_scroll_mode;
    }

    @Override
    protected void initComponents() {
        findComponentById(ResourceTable.Id_tab_image_back).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminate();
            }
        });
        findComponentById(ResourceTable.Id_tab_text_right).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                reduceTabCount();
            }
        });
        mTabSegment = (TabSegment) findComponentById(ResourceTable.Id_tabSegment);
        mContentViewPager = (PageSlider) findComponentById(ResourceTable.Id_contentViewPager);

        mPagerAdapter = new TabSegmentScrollPagerProvider();
        mContentViewPager.setProvider(mPagerAdapter);
        mContentViewPager.setCurrentPage(1, false);
        mContentViewPager.setReboundEffect(false);

        for (String page : pages) {
            mTabSegment.addTab(new TabSegment.Tab(page));
        }
        int space = AttrHelper.vp2px(16, getContext());
        mTabSegment.setHasIndicator(true);
        mTabSegment.setMode(TabSegment.MODE_SCROLLABLE);
        mTabSegment.setItemSpaceInScrollMode(space);
        mTabSegment.setupWithViewPager(mContentViewPager, false);
        mTabSegment.setPadding(space, 0, space, 0);
        mTabSegment.addOnTabSelectedListener(new TabSegment.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int index) {
                XToastUtils.toast("select " + pages[index]);
            }

            @Override
            public void onTabUnselected(int index) {
                XToastUtils.toast("unSelect " + pages[index]);
            }

            @Override
            public void onTabReselected(int index) {
                XToastUtils.toast("reSelect " + pages[index]);
            }

            @Override
            public void onDoubleTap(int index) {
                XToastUtils.toast("double tap " + pages[index]);
            }
        });

    }

    private Component getPageView(MultiPage page) {
        Component view = mPageMap.get(page);
        if (view == null) {
            Text textView = new Text(getContext());
            textView.setTextAlignment(TextAlignment.CENTER);
            textView.setText(String.format("这个是%s页面的内容", page.name()));
            textView.setTextColor(Color.GRAY);
            textView.setTextSize(50);
            view = textView;
            mPageMap.put(page, view);
        }
        return view;
    }

    public class TabSegmentScrollPagerProvider extends PageSliderProvider {

        public TabSegmentScrollPagerProvider() {
        }

        @Override
        public int getCount() {
            return mCurrentItemCount;
        }

        @Override
        public Object createPageInContainer(ComponentContainer componentContainer, int position) {
            MultiPage page = MultiPage.getPage(position);
            Component label = getPageView(page);
            label.setTag(page);
            componentContainer.addComponent(label);
            label.setLayoutConfig(new ComponentContainer.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_PARENT,
                ComponentContainer.LayoutConfig.MATCH_PARENT));
            return label;
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
            componentContainer.removeComponent((Component) o);
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object o) {
            return true;
        }
    }

    private void reduceTabCount() {
        if (mCurrentItemCount <= 1) {
            XToastUtils.toast("Only the last one, don't reduce it anymore!!!");
            return;
        }
        final int current = mContentViewPager.getCurrentPage();
        mCurrentItemCount--;
        mPagerAdapter.notifyDataChanged();
        mTabSegment.reset();
        for (int i = 0; i < mCurrentItemCount; i++) {
            mTabSegment.addTab(new TabSegment.Tab(pages[i]));
        }
        mTabSegment.notifyDataChanged();
        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                if (current > mCurrentItemCount - 1) {
                    mContentViewPager.setCurrentPage(mCurrentItemCount - 1);
                } else {
                    mContentViewPager.setCurrentPage(current);
                }
            }
        }, 100);
    }

}
